// 配置管理服务
class ConfigService {
  // 基础API URL，从全局配置中获取
  static get BASE_API_URL() {
    return process.env.API_CONFIG?.baseUrl + '/api';
  }

  /**
   * 获取配置
   * @param {string} section - 配置部分名称
   * @param {string} key - 配置项名称
   * @returns {Promise<any>} 配置值
   */
  static async getConfig(section = null, key = null) {
    try {
      let url = `${this.BASE_API_URL}/config`;
      const params = new URLSearchParams();
      if (section) params.append('section', section);
      if (key) params.append('key', key);
      
      if (params.toString()) {
        url += `?${params.toString()}`;
      }
      
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      const data = await response.json();
      if (data.success) {
        return data.data;
      } else {
        throw new Error(data.error || '获取配置失败');
      }
    } catch (error) {
      console.error('获取配置时出错:', error);
      throw error;
    }
  }

  /**
   * 更新单个配置
   * @param {string} section - 配置部分名称
   * @param {string} key - 配置项名称
   * @param {any} value - 新的配置值
   * @returns {Promise<boolean>} 是否更新成功
   */
  static async updateConfig(section, key, value) {
    try {
      const response = await fetch(`${this.BASE_API_URL}/config`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          section,
          key,
          value
        })
      });
      
      const data = await response.json();
      if (data.success) {
        return true;
      } else {
        throw new Error(data.error || '更新配置失败');
      }
    } catch (error) {
      console.error('更新配置时出错:', error);
      throw error;
    }
  }

  /**
   * 批量更新配置
   * @param {Object} updates - 要更新的配置字典，格式为 {section: {key: value}}
   * @returns {Promise<{success: boolean, failed: Array}>} 更新结果
   */
  static async bulkUpdateConfig(updates) {
    try {
      const response = await fetch(`${this.BASE_API_URL}/config/bulk`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ updates })
      });
      
      const data = await response.json();
      if (data.success) {
        return { success: true, failed: [] };
      } else {
        return { success: false, failed: data.failed || [] };
      }
    } catch (error) {
      console.error('批量更新配置时出错:', error);
      throw error;
    }
  }

  /**
   * 获取模型配置
   * @returns {Promise<Object>} 模型配置
   */
  static async getModelConfig() {
    try {
      const response = await fetch(`${this.BASE_API_URL}/config/model`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      // 检查响应状态
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP错误 ${response.status}: ${errorText || '获取模型配置失败'}`);
      }
      
      try {
        const data = await response.json();
        if (data.success) {
          // 根据用户提供的后端返回数据结构调整解析逻辑
          const modelConfig = data.data || {};
          
          // 直接返回后端数据，因为其结构已经符合前端期望的格式
          return {
            model: modelConfig.model || '',
            avatar_id: modelConfig.avatar_id || '',
            llm_type: modelConfig.llm_type || 'coze',
            llm_config: {
              // 确保llm_config的结构与前端期望的一致
              openai: modelConfig.llm?.openai || {
                api_key: '',
                model: 'gpt-3.5-turbo',
                base_url: 'https://api.openai.com/v1',
                system_prompt: '',
                stream: false,
                stream_options: {}
              },
              coze: modelConfig.llm?.coze || {
                api_token: '',
                workflow_id: '',
                base_url: 'https://api.coze.cn'
              }
            }
          };
        } else {
          throw new Error(data.error || '获取模型配置失败');
        }
      } catch (jsonError) {
        // 捕获JSON解析错误
        const rawText = await response.text();
        throw new Error(`JSON解析错误: ${jsonError.message}. 原始响应: ${rawText}`);
      }
    } catch (error) {
      console.error('获取模型配置时出错:', error);
      throw error;
    }
  }

  /**
   * 更新模型配置
   * @param {Object} config - 模型配置
   * @param {string} [config.model] - 模型名称
   * @param {string} [config.avatar_id] - 头像ID
   * @param {string} [config.llm_type] - LLM类型
   * @param {Object} [config.llm_config] - LLM配置
   * @returns {Promise<{success: boolean, failed: Array}>} 更新结果
   */
  static async updateModelConfig(config) {
    try {
      const response = await fetch(`${this.BASE_API_URL}/config/model`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(config)
      });
      
      // 检查响应状态
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP错误 ${response.status}: ${errorText || '更新模型配置失败'}`);
      }
      
      try {
        const data = await response.json();
        if (data.success) {
          return { success: true, failed: [] };
        } else {
          return { success: false, failed: data.failed || [] };
        }
      } catch (jsonError) {
        // 捕获JSON解析错误
        const rawText = await response.text();
        throw new Error(`JSON解析错误: ${jsonError.message}. 原始响应: ${rawText}`);
      }
    } catch (error) {
      console.error('更新模型配置时出错:', error);
      throw error;
    }
  }
}

export default ConfigService;